import BaseMapHandler from './BaseMapHandler';
import goFishingIcon from '../../assets/images/go-fishing.png';

export default class MoveToCurrentPositionHandler extends BaseMapHandler {
  name = '定位'
  type = 'move-to-current-position'
  description = '移动到当前位置'
  active = false
  private currentPositionMarker: any = null

  constructor() {
    super()
  }

  activate(): void {
    this.active = true
    // 尝试获取当前位置并移动到该位置
    this.getCurrentPosition()
  }

  deactivate(): void {
    this.active = false
    // 清理标记
    if (this.currentPositionMarker) {
      this.currentPositionMarker.setMap(null)
      this.currentPositionMarker = null
    }
  }

  handle(): void {
    // 处理定位请求
    this.getCurrentPosition()
  }

  private getCurrentPosition(): void {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(
        (position) => {
          const lat = position.coords.latitude
          const lng = position.coords.longitude
          this.moveToPosition(lat, lng)
        },
        (error) => {
          console.error('获取位置失败:', error)
          // 可以根据不同的错误代码显示不同的提示
          switch (error.code) {
            case error.PERMISSION_DENIED:
              alert('用户拒绝了位置请求')
              break
            case error.POSITION_UNAVAILABLE:
              alert('位置信息不可用')
              break
            case error.TIMEOUT:
              alert('获取位置超时')
              break
            default:
              alert('获取位置时发生错误')
              break
          }
        },
        {
          enableHighAccuracy: true, // 高精度定位
          timeout: 10000, // 超时时间10秒
          maximumAge: 60000 // 位置缓存时间60秒
        }
      )
    } else {
      alert('您的浏览器不支持地理定位')
    }
  }

  private moveToPosition(lat: number, lng: number): void {
    const map = (window as any).mapController.getMap()
    if (!map) {
      console.error('地图实例不存在')
      return
    }

    // 设置地图中心点和缩放级别
    map.panTo(new (window as any).qq.maps.LatLng(lat, lng))
    map.setZoom(15)

    // 添加当前位置标记
    this.addCurrentPositionMarker(lat, lng)
  }

  addCurrentPositionMarker(lat: number, lng: number): void {
    const map = (window as any).mapController.getMap()
    if (!map) {
      console.error('地图实例不存在')
      return
    }

    // 清理之前的标记
    if (this.currentPositionMarker) {
      this.currentPositionMarker.setMap(null)
    }

    // 创建新标记
    this.currentPositionMarker = new (window as any).qq.maps.Marker({
      position: new (window as any).qq.maps.LatLng(lat, lng),
      map: map,
      icon: {
        url: goFishingIcon,
        size: new (window as any).qq.maps.Size(30, 30),
        anchor: new (window as any).qq.maps.Point(15, 15)
      },
      animation: (window as any).qq.maps.MarkerAnimation.DROP,
      title: '当前位置'
    })

    // 添加点击事件监听，显示位置信息
    (window as any).qq.maps.event.addListener(this.currentPositionMarker, 'click', () => {
      this.createInfoWindow(map, { lat, lng }, `当前位置：${lat.toFixed(6)}, ${lng.toFixed(6)}`)
    })
  }
}